import React, { useState, useEffect } from "react";
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Modal,
  Form,
  Select,
  message,
  Tag,
  Tooltip,
  Upload,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UploadOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import type { Student } from "../../../types/admin";
import { useUser } from "../../../contexts/UserContext";
import PermissionGuard from "../../../components/PermissionGuard";
import FileUpload from "../../../components/FileUpload";

const { Search } = Input;
const { confirm } = Modal;

const StudentManagement: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [students, setStudents] = useState<Student[]>([
    {
      id: "s1",
      name: "李明",
      email: "liming@example.com",
      phone: "13900139000",
      class: "计算机2021级1班",
      major: "计算机科学与技术",
      status: "active",
      courses: ["高级Web开发", "数据结构"],
      createTime: "2024-01-01",
    },
  ]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingStudent, setEditingStudent] = useState<Student | null>(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState("");

  const handleSearch = (value: string) => {
    setSearchText(value);
    // TODO: 实现搜索逻辑
  };

  const handleImportCSV = async (file: File) => {
    try {
      const reader = new FileReader();
      reader.onload = async (e) => {
        const text = e.target?.result as string;
        const rows = text.split("\\n").filter((row) => row.trim());
        const headers = rows[0].split(",");

        const students = rows.slice(1).map((row) => {
          const values = row.split(",");
          return {
            studentId: values[0],
            name: values[1],
            email: values[2],
            phone: values[3],
            class: values[4],
            major: values[5],
          };
        });

        // TODO: 调用API批量创建学生
        message.success(`成功导入 ${students.length} 名学生`);
      };
      reader.readAsText(file);
    } catch (error) {
      message.error("导入失败，请检查文件格式");
    }
  };

  const showEditModal = (student: Student | null) => {
    setEditingStudent(student);
    setModalVisible(true);
    if (student) {
      form.setFieldsValue(student);
    } else {
      form.resetFields();
    }
  };

  const handleDelete = (id: string) => {
    confirm({
      title: "确认删除",
      icon: <ExclamationCircleOutlined />,
      content: "确定要删除这位学生吗？此操作不可恢复。",
      onOk: async () => {
        try {
          // TODO: 调用删除API
          setStudents(students.filter((s) => s.id !== id));
          message.success("删除成功");
        } catch (error) {
          message.error("删除失败");
        }
      },
    });
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingStudent) {
        // TODO: 调用更新API
        setStudents(
          students.map((s) =>
            s.id === editingStudent.id ? { ...s, ...values } : s
          )
        );
        message.success("更新成功");
      } else {
        // TODO: 调用创建API
        const newStudent: Student = {
          id: Date.now().toString(),
          ...values,
          createTime: new Date().toISOString().split("T")[0],
          courses: [],
        };
        setStudents([...students, newStudent]);
        message.success("创建成功");
      }
      setModalVisible(false);
    } catch (error) {
      message.error("提交失败");
    }
  };

  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "电话",
      dataIndex: "phone",
      key: "phone",
    },
    {
      title: "班级",
      dataIndex: "class",
      key: "class",
    },
    {
      title: "专业",
      dataIndex: "major",
      key: "major",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: string) => (
        <Tag color={status === "active" ? "green" : "red"}>
          {status === "active" ? "在读" : "休学"}
        </Tag>
      ),
    },
    {
      title: "选课数",
      dataIndex: "courses",
      key: "courses",
      render: (courses: string[]) => (
        <Tooltip title={courses.join(", ")}>
          <Tag color="blue">{courses.length}</Tag>
        </Tooltip>
      ),
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: Student) => (
        <Space>
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <PermissionGuard permission="student.manage">
      <div style={{ padding: "24px" }}>
        <Card>
          <Space direction="vertical" style={{ width: "100%" }}>
            <Space style={{ marginBottom: 16 }}>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => showEditModal(null)}
              >
                添加学生
              </Button>
              <Search
                placeholder="搜索学生..."
                onSearch={handleSearch}
                style={{ width: 300 }}
              />
              <FileUpload onUpload={handleImportCSV} buttonText="批量导入" />
              <Tooltip title="下载模板">
                <Button icon={<UploadOutlined />}>下载导入模板</Button>
              </Tooltip>
            </Space>

            <Table
              rowKey="id"
              columns={columns}
              dataSource={students}
              loading={loading}
              pagination={{
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
            />
          </Space>
        </Card>

        <Modal
          title={editingStudent ? "编辑学生" : "添加学生"}
          open={modalVisible}
          onOk={handleModalOk}
          onCancel={() => setModalVisible(false)}
          destroyOnClose
        >
          <Form form={form} layout="vertical">
            <Form.Item
              name="name"
              label="姓名"
              rules={[{ required: true, message: "请输入姓名" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                { required: true, message: "请输入邮箱" },
                { type: "email", message: "请输入有效的邮箱地址" },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="phone"
              label="电话"
              rules={[{ required: true, message: "请输入电话" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="class"
              label="班级"
              rules={[{ required: true, message: "请输入班级" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="major"
              label="专业"
              rules={[{ required: true, message: "请输入专业" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="status"
              label="状态"
              rules={[{ required: true, message: "请选择状态" }]}
            >
              <Select>
                <Select.Option value="active">在读</Select.Option>
                <Select.Option value="inactive">休学</Select.Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </PermissionGuard>
  );
};

export default StudentManagement;
